package com.controller;

import com.base.AjaxRequest;
import com.base.AjaxResult;
import com.base.BaseController;
import com.base.MetaInfo;
import com.bean.WebsiteMessage;
import com.bean.anno.LogAnno;
import com.github.pagehelper.PageHelper;
import com.mapper.mysql.WebsiteMessageMapper;
import com.mapper.repository.mysql.WebsiteMessageRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.List;
import java.util.UUID;

@RestController
@RequestMapping("message")
public class WebsiteMessageController extends BaseController {

    @Autowired
    private WebsiteMessageMapper websiteMessageMapper;

    @Autowired
    private WebsiteMessageRepository websiteMessageRepository;

    @LogAnno(apiName = "获取留言")
    @PostMapping("list")
    public AjaxResult list(@RequestBody AjaxRequest<WebsiteMessage> request){
        WebsiteMessage message = request.getT();
        MetaInfo metaInfo = request.getMetaInfo();

        PageHelper.startPage(metaInfo.getPage(),metaInfo.getSize());
        List<WebsiteMessage> list = websiteMessageMapper.select();

        return success("查询成功",list,metaInfo);
    }

    @LogAnno(apiName = "获取留言ById")
    @GetMapping("{id}")
    public AjaxResult getOne(@PathVariable("id") String id){
        WebsiteMessage message = websiteMessageRepository.getById(id);
        System.out.println(message.toString());
        return success("查询成功",message);
    }

    @LogAnno(apiName = "添加留言")
    @PostMapping("add")
    public AjaxResult add(@RequestBody WebsiteMessage message){
        String id = UUID.randomUUID().toString();
        message.setId(id);
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = servletRequestAttributes.getRequest();
        String addr = request.getRemoteAddr();
        message.setAddr(addr);
        message.setCreatetime(LocalDateTime.now());
        websiteMessageRepository.save(message);
        return success("新增成功");
    }

    @LogAnno(apiName = "删除留言")
    @PostMapping("del")
    public AjaxResult del(@RequestBody WebsiteMessage message){
        websiteMessageRepository.delete(message);
        return success("删除成功");
    }

    @LogAnno(apiName = "添加网址类型")
    @PostMapping("update")
    public AjaxResult update(@RequestBody WebsiteMessage message){
        message.setUpdatetime(LocalDateTime.now());
        websiteMessageRepository.save(message);
        return success("更新成功");
    }
}
